﻿
imports system.io
imports std

Public Module share

    Public sub replace(ByRef replacer As vector(Of pair(Of String, String)) _
                            , ByRef inputfile As String, ByRef outputfile As String)
        assert(Not replacer Is Nothing, "replacer should not be null.")
        dim reader as textreader=nothing
        dim writer as textwriter=nothing
        initialInput(inputfile,reader)
        initialOutput(outputfile,writer)
        assert(not reader is nothing, "cannot read file "+inputfile)
        assert(not writer is nothing, "cannot write to file "+outputfile)
        Dim i As Int64
        for i=0 to replacer.size()-1
            unescape(replacer(i).first)
            unescape(replacer(i).second)
        next
        
        dim input as string=nothing
        input=reader.readtoend()
        closestream(reader)
        If Not isemptystring(input) Then
            For i = 0 To replacer.size() - 1
                input = input.Replace(replacer(i).first, replacer(i).second)
            Next
        End If
        writer.write(input)
        closestream(writer)
    End sub

    Public sub linereplace(ByRef replacer As vector(Of pair(Of String, String)) _
                            , ByRef inputfile As String, ByRef outputfile As String)
        assert(Not replacer Is Nothing, "replacer should not be null.")
        dim reader as textreader=nothing
        dim writer as textwriter=nothing
        initialInput(inputfile,reader)
        initialOutput(outputfile,writer)
        assert(not reader is nothing, "cannot read file "+inputfile)
        assert(not writer is nothing, "cannot write to file "+outputfile)
        
        Dim i As Int64
        for i=0 to replacer.size()-1
            unescape(replacer(i).first)
            unescape(replacer(i).second)
        next

        dim input as string=nothing
        input=reader.readline()
        while not input is nothing
            kicknewlinechar(input)
            For i = 0 To replacer.size() - 1
                input = input.Replace(replacer(i).first, replacer(i).second)
            Next
            writer.writeline(input)
            input=reader.readline()
        end while
        closestream(reader)
        closestream(writer)
    End sub
End Module
